package jrain.fw.business.common;

import java.util.function.Consumer;

import jrain.fw.core.business.BusinessConst;
import jrain.fw.core.business.BusinessInterceptor;
import jrain.fw.core.business.BusinessRequest;
import jrain.fw.core.business.BusinessResponse;
import jrain.fw.core.business.client.BusinessApiClient;
import jrain.fw.core.consts.Consts;
import jrain.fw.core.service.Service;
import jrain.fw.core.service.ServiceConst;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.lang.StringUtils;

@Service(group = ServiceConst.S_BUSINESS_API_CLIENT, module = ServiceConst.M_BUSINESS)
public class BusinessApiClientService implements BusinessApiClient {

	// private static final Logger log = LoggerFactory.getLogger(BusinessApiClientService.class);
	private final String authInterceptor;
	private static final BusinessResponse RESPONSE = new BusinessResponse();

	public BusinessApiClientService() {
		authInterceptor = StringUtils.trimNull(FwUtils.getFwCfg().get(Consts.BUSINESS_AUTH));
	}

	@Override
	public BusinessResponse doSync(BusinessRequest request) {
		return doSync(request, null);
	}

	@Override
	public BusinessResponse doSync(BusinessRequest request, Consumer<BusinessRequest> consumer) {
		if (consumer != null) {
			consumer.accept(request);
		}
		BusinessResponse response = auth(request);
		if (response.getCode() == BusinessConst.RES_CODE_SUCCESS) {
			response = FwUtils.getBusinessInnerClient().doSync(request);
		}
		return response;
	}

	@Override
	public void doAsync(BusinessRequest request, Consumer<BusinessResponse> callbak) {
		doAsync(request, null, callbak);
	}

	@Override
	public void doAsync(BusinessRequest request, Consumer<BusinessRequest> consumer, Consumer<BusinessResponse> callbak) {
		if (consumer != null) {
			consumer.accept(request);
		}
		BusinessResponse response = auth(request);
		if (response.getCode() == BusinessConst.RES_CODE_SUCCESS) {
			FwUtils.getBusinessInnerClient().doAsync(request, callbak);
		} else {
			callbak.accept(response);
		}
	}

	@Override
	public String doSyncStr(BusinessRequest request) {
		return doSyncStr(request, null);
	}

	@Override
	public String doSyncStr(BusinessRequest request, Consumer<BusinessRequest> consumer) {
		BusinessResponse response = doSync(request, consumer);
		return FwUtils.getJsonService().toPageJson(response);
	}

	public BusinessResponse auth(BusinessRequest request) {
		if (authInterceptor.length() > 0) {
			BusinessInterceptor businessInterceptor = FwUtils.getBusinessProvider().getInterceptor(authInterceptor);
			if (businessInterceptor != null) {
				BusinessResponse response = businessInterceptor.handler(request);
				if (response.getCode() != BusinessConst.RES_CODE_SUCCESS) {
					return response;
				}
			}
		}
		return RESPONSE;
	}

}
